/**
 * Copyright (C) 2010 altuure <altuure [AT] gmail [DOT] com> http://www.altuure.com/projects/yagdao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.altuure.yagdao.jpa;

import com.altuure.yagdao.GenericDAO;
import com.altuure.yagdao.SearchResultList;
import com.altuure.yagdao.YLimit;
import com.altuure.yagdao.YPage;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.*;
import java.io.Serializable;
import java.util.Map;

public class GenericJpaDAO<T, ID extends Serializable> implements GenericDAO<T, ID> {
    private EntityManagerAccessor entityManagerAccessor;
    private Class objectClass;
    private String idProperty;
    private CommonJpaDAO commonDAO;

    public Class<?> getObjectClass() {
        return objectClass;
    }

    public void setObjectClass(Class newObjectClass) {
        this.objectClass = newObjectClass;
    }

    public void setEntityManagerAccessor(EntityManagerAccessor entityManagerAccessor) {
        this.entityManagerAccessor = entityManagerAccessor;


    }
    public void setCommonDAO(CommonJpaDAO commonDAO) {
        this.commonDAO = commonDAO;
    }
    /*
     * (non-Javadoc)
     * 
     * @see com.altuure.yagdao.GenericDAO#save(java.lang.Object)
     */
    public void save(Object entity) {
        getEntityManager().persist(entity);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.altuure.yagdao.GenericDAO#load(java.io.Serializable)
     */
    public T load(ID id) {
        return (T)commonDAO.load(objectClass, id);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.altuure.yagdao.GenericDAO#getAll()
     */
    public SearchResultList<T> getAll() {
        return commonDAO.getAll(objectClass);

    }

    /*
     * (non-Javadoc)
     * 
     * @see com.altuure.yagdao.GenericDAO#getAll(com.altuure.yagdao.DAOPage)
     */
    public SearchResultList<T> getAll(YPage paging) {
         return commonDAO.getAll(objectClass,paging);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.altuure.yagdao.GenericDAO#get(java.io.Serializable)
     */
    public T get(ID id) {

        return (T) commonDAO.get(objectClass, id);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.altuure.yagdao.GenericDAO#fetch(java.io.Serializable)
     */
    public T fetch(ID id) {
        return (T) commonDAO.fetch(objectClass, id);
    }



    /*
     * (non-Javadoc)
     * 
     * @see com.altuure.yagdao.GenericDAO#count()
     */
    public long count() {
       return commonDAO.count(objectClass);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.altuure.yagdao.GenericDAO#update(java.lang.Object)
     */
    public void update(Object object) {
        commonDAO.update(object);

    }

    /*
     * (non-Javadoc)
     * 
     * @see com.altuure.yagdao.GenericDAO#deleteById(java.io.Serializable)
     */
    public void deleteById(ID id) {
        commonDAO.deleteById(objectClass, id);

    }

    /*
     * (non-Javadoc)
     * 
     * @see com.altuure.yagdao.GenericDAO#delete(java.lang.Object)
     */
    public void delete(Object object) {
       commonDAO.delete(object);

    }

    /**
     * set limit for the query
     * @param query query
     * @param firstResult first result index
     * @param pageSize page size
     */
    public void setLimits(Query query, int firstResult, int pageSize) {
        setLimits(query, new YLimit(firstResult, pageSize));
    }

    /**
     * set limits for query
     * @param query query
     * @param limit page limits
     */
    public void setLimits(Query query, YLimit limit) {
        if (limit == null)
            return;
        if (limit.isPaged())
            query.setFirstResult(limit.getFirstResult());
        if (limit.isPageSized())
            query.setMaxResults(limit.getPageSize());
    }

    public SearchResultList<T> query(Query query, YLimit paging) {
        setLimits(query, paging);
        return new SearchResultList<T>(query.getResultList(), paging);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.altuure.yagdao.GenericDAO#fetchAll()
     */
    public SearchResultList<T> fetchAll() {
        return (SearchResultList<T>) commonDAO.fetchAll(objectClass);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.altuure.yagdao.GenericDAO#fetchAll(com.altuure.yagdao.DAOPage)
     */
    public SearchResultList<T> fetchAll(YPage paging) {
       return (SearchResultList<T>) commonDAO.fetchAll(objectClass,paging);
    }



    /**
     * set Orders of given criteria.
     * @param select selct
     * @param paging paging
     * @param criteriaBuilder criteria builder
     * @param from root from
     * @param joins joins map
     */
    public void setOrders(CriteriaQuery<Object> select, YPage paging, CriteriaBuilder criteriaBuilder, Root from,
            Map<String, From> joins) {
        commonDAO.setOrders(select, paging, criteriaBuilder, from, joins);

    }

    /**
     * returns the id property for given entity
     * @return id proeprty name
     */
    public String getIdProperty() {
        if (idProperty != null)
            return idProperty;
      idProperty=commonDAO.getIdProperty(objectClass);
        if (idProperty == null)
            throw new RuntimeException("id field not found");
        return idProperty;
    }

    private EntityManager getEntityManager() {
        return entityManagerAccessor.getEntityManager();
    }



    /**
     * create latest join from given root crietria from
     * @param from root
     * @param fetchs fetch map cache
     * @param strings . splited field array
     * @return get latest fetch
     */
    @SuppressWarnings("rawtypes")
    protected FetchParent getLatestFetch(Root from, Map<String, FetchParent> fetchs, String[] strings) {
        // /not implemented yet
       return commonDAO.getLatestFetch(from, fetchs, strings);
    }



    public void detach(Object entity) {
       commonDAO.detach(entity);

    }

    public void init() {
        if(commonDAO==null){
            commonDAO=new CommonJpaDAO();
            commonDAO.setEntityManagerAccessor(entityManagerAccessor);
        }

    }
}
